package com.alawn.security.config.filter;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alawn.security.service.SecurityService;

/**
 * @Description
 * @auther johnny
 * @create 2019-02-26 11:07
 */
@Service
public class ShiroFilerChainManager {

	@Autowired
	private SecurityService securityService;

	@Autowired
	private DefaultFilterChainManager filterChainManager;

	private Map<String, NamedFilterList> defaultFilterChains;

	@PostConstruct
	public void init() {
		defaultFilterChains = new HashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
		setInterceptUrl(filterChainManager);
	}

	public void initFilterChains() {
		filterChainManager.getFilterChains().clear();
		// shiro设置的默认拦截的url
		if (defaultFilterChains != null) {
			filterChainManager.getFilterChains().putAll(defaultFilterChains);
		}
		// 动态拦截的url
		setInterceptUrl(filterChainManager);
	}

	private void setInterceptUrl(DefaultFilterChainManager filterChainManager) {
		securityService.hasResources().forEach(resource -> {
			if (StringUtils.isNotBlank(resource.getUrl()) && StringUtils.isNotBlank(resource.getPermission())) {
				filterChainManager.addToChain(resource.getUrl(), "perms", resource.getPermission().trim());
			}
		});
		filterChainManager.addToChain("/**", "authc");
	}
}
